/*
 * @Author: duchengdong
 * @Date: 2021-10-13 10:14:35
 * @LastEditors: duchengdong
 * @LastEditTime: 2021-12-28 20:39:40
 * @Description:
 */
const CracoLessPlugin = require('craco-less')
const theme = require('./theme')
// npm 包版本冲突，自定义
const sassResourcesLoader = {
	overrideWebpackConfig: ({webpackConfig, pluginOptions}) => {
		// Check webpack config
		if (!webpackConfig || !webpackConfig.module || !webpackConfig.module.rules || typeof webpackConfig.module.rules !== 'object') {
			throw new Error('craco-sass-resources-loader error: no valid webpackConfig.module.rules')
		}

		// Add the loader rule where needed
		const output = {...webpackConfig}
		Object.keys(output.module.rules).forEach((ruleKey, ruleIndex) => {
			const rule = output.module.rules[ruleKey]
			if (Object.prototype.hasOwnProperty.call(rule, 'oneOf')) {
				rule.oneOf.forEach((oneOf, oneOfIndex) => {
					if (oneOf.test && oneOf.use && (`${oneOf.test}`.includes('scss') || `${oneOf.test}`.includes('sass'))) {
						const options =
							pluginOptions && pluginOptions.resources
								? {
										resources: pluginOptions.resources,
								  }
								: {}

						output.module.rules[ruleIndex].oneOf[oneOfIndex].use.push({
							loader: 'sass-resources-loader',
							options,
						})
					}
				})
			}
		})
		return output
	},
}

module.exports = {
	webpack: {
		configure:(webpackConfig,{env,paths}) => {
			webpackConfig.output ={
				...webpackConfig.output,
				publicPath: process.env.NODE_ENV=='production'?'/':'/'
			}
			return webpackConfig;
		}
	},
	plugins: [
		{
			plugin: CracoLessPlugin,
			options: {
				lessLoaderOptions: {
					lessOptions: {
						modifyVars: theme,
						javascriptEnabled: true,
					},
				},
			},
		},
		{
			plugin: sassResourcesLoader,
			options: {
				resources: './src/style/theme.scss',
			},
		},
	],
}
